package com.jinzhi.jzweb.service.impl;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.certificate.pojo.MyResultsVo;
import com.jinzhi.jzweb.dao.ExaminationResultsComDao;
import com.jinzhi.jzweb.domain.ExaminationAnswerSheetComDO;
import com.jinzhi.jzweb.domain.ExaminationResultsComDO;
import com.jinzhi.jzweb.domain.moduleConfig.CareStuSignUpComRealityDO;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.pojo.moduleConfig.*;
import com.jinzhi.jzweb.pojo.statistics.*;
import com.jinzhi.jzweb.pojo.statistics.ResulitsConfig.ProportionOfTotalScoreVo;
import com.jinzhi.jzweb.pojo.statistics.ResulitsConfig.ResulitsConfig;
import com.jinzhi.jzweb.service.ExaminationAnswerSheetComService;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.service.moduleConfig.CareStuSignUpComRealityService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ZipFileUtils;
import com.jinzhi.oss.controller.FileController;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 考试   成绩
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Service
public class ExaminationResultsComServiceImpl extends CoreServiceImpl<ExaminationResultsComDao, ExaminationResultsComDO> implements ExaminationResultsComService {

    @Autowired
    private CareStuSignUpComRealityService careStuSignUpComRealityService;

    private final FileController fileController;

    private final ExaminationAnswerSheetComService examinationAnswerSheetComService;

    private final DictService dictService;

    public ExaminationResultsComServiceImpl(FileController fileController, ExaminationAnswerSheetComService examinationAnswerSheetComService, DictService dictService) {
        this.fileController = fileController;
        this.examinationAnswerSheetComService = examinationAnswerSheetComService;
        this.dictService = dictService;
    }

    @Override
    public Page<MyResultsVo> selByUserId(Map map,int current, int number) {

        // 新建分页
        Page<MyResultsVo> page = new Page<MyResultsVo>(current, number);

        return page.setRecords(this.baseMapper.selByUserId(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findLists(Map map,int current , int number) {
        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findLists(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findPageList(Map map, int current, int number) {

        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findPageList(page,map));
    }

    @Override
    public Page<ExaminationResultsComDO> findList(Map map, int current, int number) {

        Page<ExaminationResultsComDO> page = new Page<ExaminationResultsComDO>(current, number);

        return page.setRecords(this.baseMapper.findList(page,map));
    }

	@Override
	public List<ExaminationResultsExportVo> exportList(Map map) {
		
		return this.baseMapper.exportList(map);
	}

    @Override
    public List<ExaminationResultsExportAllVo> exportListAll(Map map) {
        return this.baseMapper.exportListAll(map);
    }

    @Override
    public List<ExaminationResultsPoVo> resultList(Long ebatchId) {
        return baseMapper.resultList(ebatchId);
    }

    @Override
    public List<ExaminationResultsABCPoVo> listABC() {
        return this.baseMapper.listABC();
    }


    /**
     * 婴幼儿早期教育发展分析分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> zhiDingStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Map<String, String> map =new HashMap<>();
        map.put("field","A");
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        List<ExaminationResultsPoVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                //计算裁判平均分
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    //计算裁判打分平均分和最终得分
                    getAvgZhiDing(examinationResultsPoVo);
                }
                //考虑一名选手的情况
                if(valueList.size()==1){
                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    if(valueList.get(0).getDecrypt()==0){
                        examinationResultsPoVo.setDecrypt(0);
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    } else {
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,examinationResultsPoVo);
                        examinationResultsPoVo.setDecrypt(1);
                        examinationResultsPoVo.setRecordNumber(valueList.get(0).getRecordNumber());
                        valueList.add(examinationResultsPoVo);
                        //一人的分数即团队得分
                        double totalAverageScore = Double.parseDouble(valueList.get(0).getAverageScore());
                        valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                        valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));
                    }
                }
                //两名选手
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = averageScore.add(averageScore2);
                    valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                    valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));

                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    examinationResultsPoVo.setDecrypt(0);
                    //两个都未解密
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    }
                    //只有一个未解密
                    else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        valueList.get(0).setTotalAverageScore("******");
                        valueList.get(1).setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            valueList.remove(0);
                            valueList.add(examinationResultsPoVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            valueList.remove(1);
                            valueList.add(examinationResultsPoVo);
                        }
                    }
                }
                pageList.addAll(valueList);
            }

            //判断最高分和最低分是否隐藏
            boolean hasDecryptZero = pageList.stream()
                    .anyMatch(examinationResultsPoVo -> {
                        Integer decrypt = examinationResultsPoVo.getDecrypt();
                        return decrypt != null && decrypt == 0; // 先检查decrypt是否为null，再比较是否等于0
                    });
            if(hasDecryptZero){
                pageList.get(0).setMaxScore("******");
                pageList.get(0).setMinScore("******");
            }else{
                //获取最大值最小值
                // 获取最大值
                OptionalDouble maxScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                double maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                double minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                pageList.get(0).setMaxScore(String.valueOf(maxValue));
                pageList.get(0).setMinScore(String.valueOf(minValue));
            }
            pageList.get(0).setPeopleNumber(pageList.size());
            page.setTotal(pageList.size());
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 婴幼儿早期教育发展分析分数统计导出
     * @return
     */
    @Override
    public void zhiDingDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        Map<String, String> map =new HashMap<String, String>();
        map.put("field","A");
        List<ZhiDingScoreExcelVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                ZhiDingScoreExcelVo soreStatisticsVo = new ZhiDingScoreExcelVo();
                List<ZhiDingScoreChildrenExcelVo> childrenExcelList = new ArrayList<>();
                soreStatisticsVo.setUnitName(entry.getKey());//院校名称
                soreStatisticsVo.setRecordNumber(valueList.get(0).getRecordNumber());//检录号

                //计算裁判平均分
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    getAvgZhiDing(examinationResultsPoVo);
                    BeanUtils.copyProperties(examinationResultsPoVo,zhiDingScoreChildrenExcelVo);
                    childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                }
                //只存在一位选手的时候
                if(valueList.size()==1){
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    if(childrenExcelList.get(0).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                    }else {
                        //一位选手的得分及团队得分
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,zhiDingScoreChildrenExcelVo);
                        double totalAverageScore = Double.parseDouble(childrenExcelList.get(0).getAverageScore());//总成绩
                        soreStatisticsVo.setTotalAverageScore(String.valueOf(totalAverageScore));
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                    }
                }
                //两位选手
                if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(childrenExcelList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(childrenExcelList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = averageScore.add(averageScore2);
                    soreStatisticsVo.setTotalAverageScore(String.valueOf(totalAverageScore));
                    //判断是否已经解密
                    ZhiDingScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiDingScoreChildrenExcelVo();
                    zhiDingScoreChildrenExcelVo.setDecrypt(0);
                    if(childrenExcelList.get(0).getDecrypt()==0 && childrenExcelList.get(1).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        soreStatisticsVo = new ZhiDingScoreExcelVo();
                    } else if (childrenExcelList.get(0).getDecrypt()==0 || childrenExcelList.get(1).getDecrypt()==0) {
                        soreStatisticsVo.setTotalAverageScore("******");
                        if(childrenExcelList.get(0).getDecrypt()==0){
                            childrenExcelList.remove(0);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            childrenExcelList.remove(1);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        }
                    }
                }
                soreStatisticsVo.setScoreList(childrenExcelList);
                pageList.add(soreStatisticsVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(pageList, "婴幼儿早期教育发展分析分数导出", "婴幼儿早期教育发展分析分数导出", ZhiDingScoreExcelVo.class, "婴幼儿早期教育发展分析分数导出", response);
    }

    /**
     * 职业素养测评分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> zhiYeStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Map<String, String> map =new HashMap<>();
        map.put("field","C");
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        List<ExaminationResultsPoVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                //考虑一名选手的情况
                if(valueList.size()==1){
                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    if(valueList.get(0).getDecrypt()==0){
                        examinationResultsPoVo.setDecrypt(0);
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    } else {
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,examinationResultsPoVo);
                        examinationResultsPoVo.setDecrypt(1);
                        examinationResultsPoVo.setRecordNumber(valueList.get(0).getRecordNumber());
                        valueList.add(examinationResultsPoVo);
                        //一人的分数即团队得分
                        double totalAverageScore = Double.parseDouble(valueList.get(0).getAverageScore());
                        valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                        valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));
                    }
                }
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = averageScore.add(averageScore2);
                    valueList.get(0).setTotalAverageScore(String.valueOf(totalAverageScore));
                    valueList.get(1).setTotalAverageScore(String.valueOf(totalAverageScore));

                    //判断是否已经解密
                    ExaminationResultsPoVo examinationResultsPoVo = new ExaminationResultsPoVo();
                    examinationResultsPoVo.setDecrypt(0);
                    //两个都未解密
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        valueList = new ArrayList<>();
                        valueList.add(examinationResultsPoVo);
                        valueList.add(examinationResultsPoVo);
                    }
                    //一个已经解密
                    else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        valueList.get(0).setTotalAverageScore("******");
                        valueList.get(1).setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            valueList.remove(0);
                            valueList.add(examinationResultsPoVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            valueList.remove(1);
                            valueList.add(examinationResultsPoVo);
                        }
                    }
                }
                pageList.addAll(valueList);
            }

            //判断最高分和最低分是否隐藏
            boolean hasDecryptZero = pageList.stream()
                    .anyMatch(examinationResultsPoVo -> {
                        Integer decrypt = examinationResultsPoVo.getDecrypt();
                        return decrypt != null && decrypt == 0; // 先检查decrypt是否为null，再比较是否等于0
                    });
            if(hasDecryptZero){
                pageList.get(0).setMaxScore("******");
                pageList.get(0).setMinScore("******");
            }else{
                //获取最大值最小值
                // 获取最大值
                OptionalDouble maxScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                double maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = pageList.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                double minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                pageList.get(0).setMaxScore(String.valueOf(maxValue));
                pageList.get(0).setMinScore(String.valueOf(minValue));
            }
            pageList.get(0).setPeopleNumber(pageList.size());
            page.setTotal(pageList.size());
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 职业素养测评分数导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void zhiYeDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        Map<String, String> map =new HashMap<String, String>();
        map.put("field","C");
        List<ZhiYeScoreExcelVo> pageList = new ArrayList<>();
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        if(null!=examinationResultsPoVos && !examinationResultsPoVos.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = examinationResultsPoVos.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){
                List<ExaminationResultsPoVo> valueList = entry.getValue();
                ZhiYeScoreExcelVo zhiDingScoreExcelVo = new ZhiYeScoreExcelVo();
                List<ZhiYeScoreChildrenExcelVo> childrenExcelList = new ArrayList<>();
                zhiDingScoreExcelVo.setUnitName(entry.getKey());//院校名称
                zhiDingScoreExcelVo.setRecordNumber(valueList.get(0).getRecordNumber());//检录号
                for (ExaminationResultsPoVo examinationResultsPoVo : valueList) {
                    ZhiYeScoreChildrenExcelVo zhiYeScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    BeanUtils.copyProperties(examinationResultsPoVo,zhiYeScoreChildrenExcelVo);
                    childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                }
                //一位选手的情况
                if(valueList.size()==1){
                    ZhiYeScoreChildrenExcelVo zhiYeScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    if(childrenExcelList.get(0).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                    }else {
                        //一位选手的得分及团队得分
                        ExaminationResultsCopyPoVo examinationResultsCopyPoVo = new ExaminationResultsCopyPoVo();
                        BeanUtils.copyProperties(examinationResultsCopyPoVo,zhiYeScoreChildrenExcelVo);
                        zhiDingScoreExcelVo.setTotalAverageScore(String.valueOf(valueList.get(0).getAverageScore()));//总成绩
                        childrenExcelList.add(zhiYeScoreChildrenExcelVo);
                    }

                }
                else if(valueList.size()>1){
                    //计算团队得分
                    BigDecimal averageScore = new BigDecimal(valueList.get(0).getAverageScore());
                    BigDecimal averageScore2 = new BigDecimal(valueList.get(1).getAverageScore());
                    BigDecimal totalAverageScore = averageScore.add(averageScore2);
                    zhiDingScoreExcelVo.setTotalAverageScore(String.valueOf(totalAverageScore));
                    //判断是否已经解密
                    ZhiYeScoreChildrenExcelVo zhiDingScoreChildrenExcelVo = new ZhiYeScoreChildrenExcelVo();
                    zhiDingScoreChildrenExcelVo.setDecrypt(0);
                    if(valueList.get(0).getDecrypt()==0 && valueList.get(1).getDecrypt()==0){
                        childrenExcelList = new ArrayList<>();
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        zhiDingScoreExcelVo = new ZhiYeScoreExcelVo();
                    } else if (valueList.get(0).getDecrypt()==0 || valueList.get(1).getDecrypt()==0) {
                        zhiDingScoreExcelVo.setTotalAverageScore("******");
                        if(valueList.get(0).getDecrypt()==0){
                            childrenExcelList.remove(0);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        } else if (valueList.get(1).getDecrypt()==0) {
                            childrenExcelList.remove(1);
                            childrenExcelList.add(zhiDingScoreChildrenExcelVo);
                        }
                    }
                }
                zhiDingScoreExcelVo.setScoreList(childrenExcelList);
                pageList.add(zhiDingScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(pageList, "职业素养测评分数导出", "职业素养测评分数导出", ZhiYeScoreExcelVo.class, "职业素养测评分数导出", response);
    }

    /**
     * 实操居家场景分数统计
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> juJiaStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        Map<String, String> map =new HashMap<String, String>();
        map.put("field","B1");
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        boolean flag = false;//用来判断是否显示最高分最低分
        if (examinationResultsPoVos!=null && !examinationResultsPoVos.isEmpty()) {
            int i=0;
            for (ExaminationResultsPoVo examinationResultsPoVo : examinationResultsPoVos) {
                if(examinationResultsPoVo.getDecrypt()==0){
                    examinationResultsPoVos.set(i, new ExaminationResultsPoVo()); // 将满足条件的元素设置为null
                    flag = true;
                }else{
                    //计算裁判打分平均分和最终得分
                    getAvgJuJia(examinationResultsPoVo);
                }
                i+=1;
            }
            if(flag){
                examinationResultsPoVos.get(0).setMaxScore("******");
                examinationResultsPoVos.get(0).setMinScore("******");
            }else{
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                double maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                double minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                examinationResultsPoVos.get(0).setMaxScore(String.valueOf(maxValue));
                examinationResultsPoVos.get(0).setMinScore(String.valueOf(minValue));
            }
            examinationResultsPoVos.get(0).setPeopleNumber(examinationResultsPoVos.size());
            page.setRecords(examinationResultsPoVos);
            page.setTotal(examinationResultsPoVos.size());
        }

        return page;
    }


    /**
     * 实操居家场景分数统计导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void juJiaDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        examinationAnswerSheetComDT.setPageNumber(1);
        examinationAnswerSheetComDT.setPageSize(9999);
        List<ExaminationResultsPoVo> records = this.juJiaStatistics(examinationAnswerSheetComDT).getRecords();
        List<JuJiaScoreExcelVo> juJiaScoreExcelVoList = new ArrayList<>();
        if (records!=null && !records.isEmpty()) {
            for (ExaminationResultsPoVo record : records) {
                JuJiaScoreExcelVo juJiaScoreExcelVo = new JuJiaScoreExcelVo();
                BeanUtils.copyProperties(record,juJiaScoreExcelVo);
                juJiaScoreExcelVoList.add(juJiaScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(juJiaScoreExcelVoList, "实操居家场景分数统计导出", "实操居家场景分数统计导出", JuJiaScoreExcelVo.class, "实操居家场景分数统计导出", response);
    }

    /**
     * 月子中心场景成绩统计
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public Page<ExaminationResultsPoVo> yueZiStatistics(ExaminationResultsComDO examinationResultsComDO) {
        Page<ExaminationResultsPoVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页
        Map<String, String> map =new HashMap<>();
        map.put("field","B2");
        List<ExaminationResultsPoVo> examinationResultsPoVos = this.baseMapper.listScore(map);
        boolean flag = false;//用来判断是否显示最高分最低分
        if (examinationResultsPoVos!=null && !examinationResultsPoVos.isEmpty()) {
            int i=0;
            for (ExaminationResultsPoVo examinationResultsPoVo : examinationResultsPoVos) {
                if(examinationResultsPoVo.getDecrypt()==0){
                    examinationResultsPoVos.set(i, new ExaminationResultsPoVo()); // 将满足条件的元素设置为null
                    flag = true;
                }else{
                    //计算裁判打分平均分和最终得分
                    getAvgJuJia(examinationResultsPoVo);
                }
                i+=1;
            }
            if(flag){
                examinationResultsPoVos.get(0).setMaxScore("******");
                examinationResultsPoVos.get(0).setMinScore("******");
            }else{
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                double maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = examinationResultsPoVos.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                double minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                examinationResultsPoVos.get(0).setMaxScore(String.valueOf(maxValue));
                examinationResultsPoVos.get(0).setMinScore(String.valueOf(minValue));
            }
            examinationResultsPoVos.get(0).setPeopleNumber(examinationResultsPoVos.size());
            page.setRecords(examinationResultsPoVos);
            page.setTotal(examinationResultsPoVos.size());
        }

        return page;
    }

    /**
     * 月子中心场景分数统计导出
     * @param response
     * @param examinationAnswerSheetComDT
     */
    @Override
    public void yueZiDownloadImport(HttpServletResponse response, ExaminationResultsComDO examinationAnswerSheetComDT) {
        examinationAnswerSheetComDT.setPageNumber(1);
        examinationAnswerSheetComDT.setPageSize(9999);
        List<ExaminationResultsPoVo> records = this.yueZiStatistics(examinationAnswerSheetComDT).getRecords();
        List<JuJiaScoreExcelVo> juJiaScoreExcelVoList = new ArrayList<>();
        if (records!=null && !records.isEmpty()) {
            for (ExaminationResultsPoVo record : records) {
                JuJiaScoreExcelVo juJiaScoreExcelVo = new JuJiaScoreExcelVo();
                BeanUtils.copyProperties(record,juJiaScoreExcelVo);
                juJiaScoreExcelVoList.add(juJiaScoreExcelVo);
            }
        }
        //导出操作
        EasyPoiUtil.exportExcel(juJiaScoreExcelVoList, "月子中心场景分数统计导出", "月子中心场景分数统计导出", JuJiaScoreExcelVo.class, "月子中心场景分数统计导出", response);
    }

    /**
     * 成绩总统计
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public Page<OverallStatisticsVo> overallStatistics(ExaminationResultsComDO examinationResultsComDO) {
        //判断是都已经全部解密
        boolean flag = false;
        Map<String,OverallStatisticsVo> map = new HashMap<>();
        //查询学校信息
        List<CareStuSignUpComRealityDO> unitNameList = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>().groupBy("unit_name"));
        for (CareStuSignUpComRealityDO careStuSignUpComRealityDO : unitNameList) {
            if(careStuSignUpComRealityDO.getDecryptAll()==0){
                flag = true;
            }
            OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
            BeanUtils.copyProperties(careStuSignUpComRealityDO,overallStatisticsVo);
            map.put(careStuSignUpComRealityDO.getUnitName(),overallStatisticsVo);
        }
        //查询A赛场婴幼儿早期教育发展分析成绩
        Map<String, String> mapA =new HashMap<>();
        mapA.put("field","A");
        List<ExaminationResultsPoVo> listA = this.baseMapper.listScore(mapA);

        //查询C赛场职业素养测评成绩
        Map<String, String> mapC =new HashMap<String, String>();
        mapC.put("field","C");
        List<ExaminationResultsPoVo> listC = this.baseMapper.listScore(mapC);

        //查询B赛场居家场景成绩
        Map<String, String> mapB1 =new HashMap<>();
        mapB1.put("field","B1");
        List<ExaminationResultsPoVo> listB1 = this.baseMapper.listScore(mapB1);

        //查询B赛场月子场景成绩
        Map<String, String> mapB2 =new HashMap<String, String>();
        mapB2.put("field","B2");
        List<ExaminationResultsPoVo> listB2 = this.baseMapper.listScore(mapB2);

        //婴幼儿早期教育发展分析
        if(listA!=null && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                String name = examinationResultsPoVo.getName();
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();
                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgZhiDing(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = map.get(unitName);
                //选手一
                if(null==overallStatisticsVo.getNameA1() || overallStatisticsVo.getNameA1().equals("-")){
                    BeanUtils.copyProperties(examinationResultsPoVo,overallStatisticsVo);
                    overallStatisticsVo.setNameA1(name);//参赛选手
                    overallStatisticsVo.setNum1A1(num1);//一次加密
                    overallStatisticsVo.setNum2A1(num2);//二次加密
                    overallStatisticsVo.setScoreA1(examinationResultsPoVo.getJudgment());//裁判每项打分
                    overallStatisticsVo.setAvg1(Double.parseDouble(examinationResultsPoVo.getAverageScore()));//裁判打分平均分
                    map.replace(unitName,overallStatisticsVo);
                }
                else{
                    //选手二
                    overallStatisticsVo.setNameA2(name);//参赛选手
                    overallStatisticsVo.setNum1A2(num1);//一次加密
                    overallStatisticsVo.setNum2A2(num2);//二次加密
                    overallStatisticsVo.setScoreA2(examinationResultsPoVo.getJudgment());//裁判每项打分
                    overallStatisticsVo.setAvg2(Double.parseDouble(examinationResultsPoVo.getAverageScore()));//裁判打分平均分
                    overallStatisticsVo.setTotalScoreA(String.valueOf(overallStatisticsVo.getAvg1() + overallStatisticsVo.getAvg2()));//婴幼儿早期教育发展分析最终得分
                    map.replace(examinationResultsPoVo.getUnitName(),overallStatisticsVo);
                }
            }
        }
        //居家场景
        if(listB1!=null && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();

                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgJuJia(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                overallStatisticsVo.setRecordNumber(examinationResultsPoVo.getRecordNumber());
                overallStatisticsVo.setUnitName(unitName);
                overallStatisticsVo.setDecrypt(examinationResultsPoVo.getDecrypt());
                overallStatisticsVo.setNum1B1(num1);//一次加密
                overallStatisticsVo.setNum2B1(num2);//二次加密
                overallStatisticsVo.setScoreB1One(examinationResultsPoVo.getJudgment());//居家场景婴幼儿照护打分
                overallStatisticsVo.setScoreB1Two(examinationResultsPoVo.getJudgment2());//居家场景产妇照护打分打分
                overallStatisticsVo.setTotalScoreB1(examinationResultsPoVo.getTotalAverageScore());//裁判打分平均分

                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else {
                    map.put(unitName,overallStatisticsVo);
                }
            }
        }
        //月子场景
        if(listB2!=null && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                String num1 = examinationResultsPoVo.getNum1();
                String num2 = examinationResultsPoVo.getNum2();
                String unitName = examinationResultsPoVo.getUnitName();

                /** 判断是否解密 并且计算裁判打分平均分 */
                getAvgJuJia(examinationResultsPoVo);

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                overallStatisticsVo.setRecordNumber(examinationResultsPoVo.getRecordNumber());
                overallStatisticsVo.setUnitName(unitName);
                overallStatisticsVo.setDecrypt(examinationResultsPoVo.getDecrypt());
                overallStatisticsVo.setNum1B2(num1);//一次加密
                overallStatisticsVo.setNum2B2(num2);//二次加密
                overallStatisticsVo.setScoreB2One(examinationResultsPoVo.getJudgment());//居家场景婴幼儿照护打分
                overallStatisticsVo.setScoreB2Two(examinationResultsPoVo.getJudgment2());//居家场景产妇照护打分打分
                overallStatisticsVo.setTotalScoreB2(examinationResultsPoVo.getTotalAverageScore());//裁判打分平均分
                map.replace(unitName,overallStatisticsVo);
                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else{
                    map.put(unitName,overallStatisticsVo);
                }

            }
        }
        //职业素养测评
        if(listC!=null && !listC.isEmpty()){
            Map<String, List<ExaminationResultsPoVo>> groupedMap = listC.stream()
                    .collect(Collectors.groupingBy(ExaminationResultsPoVo::getUnitName));
            for (Map.Entry<String, List<ExaminationResultsPoVo>> entry : groupedMap.entrySet()){

                String unitName = entry.getKey();

                OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                if(map.containsKey(unitName)){
                    overallStatisticsVo = map.get(unitName);
                }
                List<ExaminationResultsPoVo> valueList = entry.getValue();

                //计算团队得分
                if(valueList.size()==2){
                    overallStatisticsVo.setNameC1(valueList.get(0).getName());//选手姓名
                    overallStatisticsVo.setNum1C1(valueList.get(0).getNum1());//一次加密
                    overallStatisticsVo.setNum2C1(valueList.get(0).getNum2());//二次加密
                    overallStatisticsVo.setScoreC1(valueList.get(0).getAverageScore());//素养测评考试得分
                    overallStatisticsVo.setTotalScoreC(valueList.get(0).getAverageScore());//C赛场总得分

                    overallStatisticsVo.setNameC2(valueList.get(1).getName());
                    overallStatisticsVo.setNum1C2(valueList.get(1).getNum1());
                    overallStatisticsVo.setNum2C2(valueList.get(1).getNum2());
                    overallStatisticsVo.setScoreC2(valueList.get(1).getAverageScore());
                    BigDecimal scoreC1 = new BigDecimal(overallStatisticsVo.getScoreC1());
                    BigDecimal scoreC2 = new BigDecimal(overallStatisticsVo.getScoreC2());
                    overallStatisticsVo.setTotalScoreC(String.valueOf(scoreC1.add(scoreC2)));
                }
                if(map.containsKey(unitName)){
                    map.replace(unitName,overallStatisticsVo);
                }else{
                    map.put(unitName,overallStatisticsVo);
                }
            }
        }
        Page<OverallStatisticsVo> page = new Page<>(examinationResultsComDO.getPageNumber(), examinationResultsComDO.getPageSize());//分页

        List<OverallStatisticsVo> list = new ArrayList<>();
        if(!map.isEmpty()){
            for (Map.Entry<String, OverallStatisticsVo> entry : map.entrySet()){
                OverallStatisticsVo value = entry.getValue();
                BigDecimal totalScoreA = new BigDecimal(0);
                BigDecimal totalScoreB1 = new BigDecimal(0);
                BigDecimal totalScoreB2 = new BigDecimal(0);
                BigDecimal totalScoreC = new BigDecimal(0);
                BigDecimal totalAverageScore = new BigDecimal(0);
                //计算总分
                if(!value.getTotalScoreA().equals("-")){
                    totalScoreA = new BigDecimal(value.getTotalScoreA());
                }
                if(!value.getTotalScoreB1().equals("-")){
                    totalScoreB1 = new BigDecimal(value.getTotalScoreB1());
                }
                if(!value.getTotalScoreB2().equals("-")){
                    totalScoreB2 = new BigDecimal(value.getTotalScoreB2());
                }
                if(!value.getTotalScoreC().equals("-")){
                    totalScoreC = new BigDecimal(value.getTotalScoreC());
                }
                totalAverageScore = totalScoreA.add(totalScoreB1).add(totalScoreB2).add(totalScoreC);;
                value.setTotalAverageScore(String.valueOf(totalAverageScore));
                list.add(value);
            }

            if(flag){
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    OverallStatisticsVo overallStatisticsVo = new OverallStatisticsVo();
                    OverallStatisticsCopyVo overallStatisticsCopyVo = new OverallStatisticsCopyVo();
                    BeanUtils.copyProperties(overallStatisticsCopyVo,overallStatisticsVo);
                    list.set(i,overallStatisticsVo);
                }
            }else {
                //获取最高分
                //获取最大值
                OptionalDouble maxScore = list.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .max();
                double maxValue = maxScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                // 获取最小值
                OptionalDouble minScore = list.stream()
                        .mapToDouble(examinationResultsPoVo -> {
                            // 假设getTotalAverageScore()返回的是String类型的分数
                            String scoreString = examinationResultsPoVo.getTotalAverageScore();
                            // 将String类型的分数转换为double类型
                            return Double.parseDouble(scoreString);
                        })
                        .min();
                double minValue = minScore.orElse(Double.NaN); // 如果列表为空，则返回NaN
                list.get(0).setMaxScore(String.valueOf(maxValue));
                list.get(0).setMinScore(String.valueOf(minValue));
                list.get(0).setPeopleNumber(list.size() * 2);
                page.setTotal(list.size());
            }
        }

        page.setRecords(list);
        return page;
    }

    /**
     * 获取婴幼儿早期教育发展分析裁判打分平均分
     * @param examinationResultsPoVo
     */
    public void getAvgZhiDing(ExaminationResultsPoVo examinationResultsPoVo){
        double all = 0.0;
        double avg = 0.0;
        String judgment = "-";//裁判打分 例：50/50/50
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4())
                    + Double.valueOf(examinationResultsPoVo.getScore5());
            avg = Math.round((all / 5) * 100.0) / 100.0;
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3() +"/"+ examinationResultsPoVo.getScore4() +"/"+ examinationResultsPoVo.getScore5();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4());
            avg = Math.round((all / 4) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5("-");
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3() +"/"+ examinationResultsPoVo.getScore4();
        }
        //三位
        else {
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3());
            avg = Math.round((all / 3) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5("-");
            examinationResultsPoVo.setScore4("-");
            judgment = examinationResultsPoVo.getScore1() +"/"+ examinationResultsPoVo.getScore2() +"/"+ examinationResultsPoVo.getScore3();
        }
        examinationResultsPoVo.setAverageScore(String.valueOf(avg));
        examinationResultsPoVo.setJudgment(judgment);
    }

    /**
     * 获取居家场景裁判打分平均分
     * @param examinationResultsPoVo
     */
    public void getAvgJuJia(ExaminationResultsPoVo examinationResultsPoVo){
        double all = 0.0;//婴幼儿照护总分
        double avg = 0.0;//婴幼儿照护平均分
        String judgment = "";//裁判打分
        //计算最终得分
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4())
                    + Double.valueOf(examinationResultsPoVo.getScore5());
            avg = Math.round((all / 5) * 100.0) / 100.0;
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3() + "/" + examinationResultsPoVo.getScore4() + "/" + examinationResultsPoVo.getScore5();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4())!=-1){
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3()) + Double.valueOf(examinationResultsPoVo.getScore4());
            avg = Math.round((all / 4) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5("-");
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3() + "/" + examinationResultsPoVo.getScore4();
        }
        //三位
        else {
            all = Double.parseDouble(examinationResultsPoVo.getScore1()) + Double.parseDouble(examinationResultsPoVo.getScore2())
                    + Double.parseDouble(examinationResultsPoVo.getScore3());
            avg = Math.round((all / 3) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5("-");
            examinationResultsPoVo.setScore4("-");
            judgment = examinationResultsPoVo.getScore1() + "/" + examinationResultsPoVo.getScore2() + "/" + examinationResultsPoVo.getScore3();
        }

        double allS = 0.0;//产妇照护总分
        double avgS = 0.0;//产妇照护总分
        String judgment1 = "";//裁判打分
        //五位裁判
        if(Double.valueOf(examinationResultsPoVo.getScore5s())!=-1){
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s()) + Double.valueOf(examinationResultsPoVo.getScore4s())
                    + Double.valueOf(examinationResultsPoVo.getScore5s());
            avgS = Math.round((allS / 5) * 100.0) / 100.0;
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s() + "/" + examinationResultsPoVo.getScore4s() + "/" + examinationResultsPoVo.getScore5s();
        }
        //四位裁判
        else if (Double.valueOf(examinationResultsPoVo.getScore4s())!=-1){
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s()) + Double.valueOf(examinationResultsPoVo.getScore4s());
            avgS = Math.round((allS / 4) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5s("-");
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s() + "/" + examinationResultsPoVo.getScore4s();
        }
        //三位
        else {
            allS = Double.parseDouble(examinationResultsPoVo.getScore1s()) + Double.parseDouble(examinationResultsPoVo.getScore2s())
                    + Double.parseDouble(examinationResultsPoVo.getScore3s());
            avgS = Math.round((allS / 3) * 100.0) / 100.0;
            examinationResultsPoVo.setScore5s("-");
            examinationResultsPoVo.setScore4s("-");
            judgment1 = examinationResultsPoVo.getScore1s() + "/" + examinationResultsPoVo.getScore2s() + "/" + examinationResultsPoVo.getScore3s();
        }
        BigDecimal avgDecimal = new BigDecimal(avg);
        BigDecimal avgSDecimal = new BigDecimal(avgS);
        examinationResultsPoVo.setTotalAverageScore(String.valueOf(avgDecimal.add(avgSDecimal).setScale(2, RoundingMode.HALF_UP)));//选手最终得分
        examinationResultsPoVo.setAverageScore1(avg);
        examinationResultsPoVo.setAverageScore2(avgS);
        examinationResultsPoVo.setJudgment(judgment);
        examinationResultsPoVo.setJudgment2(judgment1);
    }

    /**
     * 成绩总统计导出
     * @param examinationResultsComDO
     * @return
     */
    @Override
    public void overallStatisticsDownloadImport(HttpServletResponse response,ExaminationResultsComDO examinationResultsComDO) {
        examinationResultsComDO.setPageSize(999);
        examinationResultsComDO.setPageNumber(1);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();

        //导出操作
        EasyPoiUtil.exportExcel(records, "成绩总统计导出", "成绩总统计导出", OverallStatisticsVo.class, "成绩总统计导出", response);
    }

    /**
     * 成绩公式表导出
     * @param response
     * @param examinationResultsComDO
     */
    @Override
    public void documentWord(HttpServletResponse response, ExaminationResultsComDO examinationResultsComDO) throws Exception {
        examinationResultsComDO.setPageSize(999);
        examinationResultsComDO.setPageNumber(1);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();

        //导出组装数据
        Map<String,Object> params =new HashMap<>();
        //暂定
        params.put("batchName","母婴照护");
        List<OverallStatisticsVo> listStu = new ArrayList<>();
        if(records!=null && !records.isEmpty()){
            listStu = records.stream()
                    .filter(vo -> !"-".equals(vo.getTotalAverageScore()) && !"******".equals(vo.getTotalAverageScore()))
                    .sorted((vo1, vo2) -> {
                        try {
                            double score1 = Double.parseDouble(vo1.getTotalAverageScore());
                            double score2 = Double.parseDouble(vo2.getTotalAverageScore());
                            return Double.compare(score2, score1); // 降序排序
                        } catch (NumberFormatException e) {
                            // 处理无法解析的情况，可以决定它们的相对顺序
                            // 这里假设无法解析的字符串应被视为最低分数
                            return 1; // vo1 排在 vo2 后面，实现降序效果
                        }
                    })
                    .collect(Collectors.toList());
            for (int i = 1; i <= listStu.size(); i++) {
                listStu.get(i-1).setSort(i);
            }
        }


        params.put("listStu",listStu);

        XWPFDocument word = WordExportUtil.exportWord07(templateFile().getPath(),params);
        response.setHeader("content-disposition","attachment;filename="+new String("成绩公示表.docx".getBytes(),"ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        word.write(response.getOutputStream());
    }

    //获取docx文件位置
    private File templateFile() throws IOException {

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("scoreTemplate.docx");
        if (inputStream == null) {
            throw new RuntimeException("Template file not found in resources");
        }

        // 将输入流转换为临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile("template", ".docx");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        tempFile.deleteOnExit(); // 在JVM退出时删除临时文件
        Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return tempFile;
    }

    /**
     * 各模块得分统计数据
     */
    @Override
    public Result<?> moduleScoreList() {
        ExaminationCostStatisticModuleScoreVo resultVO = new ExaminationCostStatisticModuleScoreVo();
        List<Double> fullList = new ArrayList<>();/** 满分 */
        fullList.add(10.0);
        fullList.add(20.0);
        fullList.add(15.0);
        fullList.add(20.0);
        fullList.add(15.0);
        fullList.add(20.0);
        List<Double> nationList = new ArrayList<>();/** 各模块得分*/
        List<Double> highestList = new ArrayList<>();/** 最高分 */
        List<Double> lowestList = new ArrayList<>();/** 最低分 */
        List<Double> averageList = new ArrayList<>();/** 平均分 */
        List<Double> poorList = new ArrayList<>();/** 分差 */

        //查询婴幼儿早期教育发展分析裁判打分
        Map<String, String> mapA =new HashMap<>();
        mapA.put("field","A");
        List<ExaminationResultsPoVo> listA = this.baseMapper.listScoreByField(mapA);
        if(null!=listA && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                getAvgZhiDing(examinationResultsPoVo);
            }
            getScoreNums(highestList, lowestList, averageList, poorList, listA);
        }else{
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询B赛场居家场景成绩
        Map<String, String> mapB1 =new HashMap<>();
        mapB1.put("field","B1");
        List<ExaminationResultsPoVo> listB1 = this.baseMapper.listScoreByField(mapB1);
        if(listB1!=null && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                getAvgJuJia(examinationResultsPoVo);
            }
            //计算婴幼儿照护分数（最高、最低、平均、分差）
            getScoreNums2(highestList, lowestList, averageList, poorList, listB1);
        }else {
            addList(highestList,lowestList,averageList,poorList);
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询B赛场月子场景成绩
        Map<String, String> mapB2 =new HashMap<String, String>();
        mapB2.put("field","B2");
        List<ExaminationResultsPoVo> listB2 = this.baseMapper.listScoreByField(mapB2);
        if(listB2!=null && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                getAvgJuJia(examinationResultsPoVo);
            }
            //计算婴幼儿照护分数（最高、最低、平均、分差）
            getScoreNums2(highestList, lowestList, averageList, poorList, listB2);
        }else{
            addList(highestList,lowestList,averageList,poorList);
            addList(highestList,lowestList,averageList,poorList);
        }

        //查询C赛场职业素养测评成绩
        Map<String, String> mapC =new HashMap<String, String>();
        mapC.put("field","C");
        List<ExaminationResultsPoVo> listC = this.baseMapper.listScoreByField(mapC);
        if(listC!=null && !listC.isEmpty()){
            //计算（最高、最低、平均、分差）
            getScoreNums(highestList, lowestList, averageList, poorList, listC);
        }else {
            addList(highestList,lowestList,averageList,poorList);
        }


        resultVO.setNationList(nationList);
        resultVO.setFullList(fullList);
        resultVO.setHighestList(highestList);
        resultVO.setLowestList(lowestList);
        resultVO.setAverageList(averageList);
        resultVO.setPoorList(poorList);
        return Result.ok(resultVO);
    }

    //获取实操最高、最低、平均、分差
    private void getScoreNums(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, List<ExaminationResultsPoVo> listA) {
        double maxScore = Double.parseDouble(Collections.max(listA, Comparator.comparingDouble(poVo->Double.parseDouble(poVo.getAverageScore()))).getAverageScore());
        double minScore = Double.parseDouble(Collections.min(listA, Comparator.comparingDouble(poVo->Double.parseDouble(poVo.getAverageScore()))).getAverageScore());
        double averageScore = Math.round((listA.stream().mapToDouble(poVo->Double.parseDouble(poVo.getAverageScore())).average().orElse(0))* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore, minScore, averageScore);
    }

    //计算分差
    private void getScorePoor(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, double maxScore, double minScore, double averageScore) {
        // 防止精度丢失 将double转换为String，然后再创建BigDecimal对象
        BigDecimal maxDecimal = new BigDecimal(Double.toString(maxScore));
        BigDecimal minDecimal = new BigDecimal(Double.toString(minScore));
        double poor = maxDecimal.subtract(minDecimal).doubleValue();
        highestList.add(maxScore);
        lowestList.add(minScore);
        averageList.add(averageScore);
        poorList.add(poor);
    }

    //获取职业素养测评和婴幼儿早期教育发展分析最高、最低、平均、分差
    private void getScoreNums2(List<Double> highestList, List<Double> lowestList, List<Double> averageList, List<Double> poorList, List<ExaminationResultsPoVo> list) {
        //计算婴幼儿照护分数（最高、最低、平均、分差）
        double maxScore = Collections.max(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore1)).getAverageScore1();
        double minScore = Collections.min(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore1)).getAverageScore1();
        double averageScore = Math.round(list.stream().mapToDouble(ExaminationResultsPoVo::getAverageScore1).average().orElse(0)* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore, minScore, averageScore);
        //计算产妇照护分数（最高、最低、平均、分差）
        double maxScore2 = Collections.max(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore2)).getAverageScore2();
        double minScore2 = Collections.min(list, Comparator.comparingDouble(ExaminationResultsPoVo::getAverageScore2)).getAverageScore2();
        double averageScore2 = Math.round(list.stream().mapToDouble(ExaminationResultsPoVo::getAverageScore2).average().orElse(0)* 100.0)/ 100.0;
        getScorePoor(highestList, lowestList, averageList, poorList, maxScore2, minScore2, averageScore2);
    }

    public void addList(List<Double> highestList,List<Double> lowestList,List<Double> averageList,List<Double> poorList){
        highestList.add(0.0);
        lowestList.add(0.0);
        averageList.add(0.0);
        poorList.add(0.0);
    }


    /**
     * 总得分占比
     * @return
     */
    @Override
    public Result<?> totalScoreList() {
        ExaminationCostStatisticTotalScoreVo resultVO = new ExaminationCostStatisticTotalScoreVo();
        List<String> totalScoreList = new ArrayList<>(); /** 总得分占比折线图 */
        List<NationVo> totalScorePercentage = new ArrayList<>(); /** 总得分占比 饼图 */
        List<Double> scoreList = new ArrayList<>();
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        examinationResultsComDO.setPageNumber(1);
        examinationResultsComDO.setPageSize(999);
        List<OverallStatisticsVo> records = overallStatistics(examinationResultsComDO).getRecords();
        if(null!=records && !records.isEmpty()){
            for (OverallStatisticsVo record : records) {
                if(record.getTotalAverageScore()!=null && !record.getTotalAverageScore().equals("-") && !record.getTotalScoreA().equals("******")){
                    scoreList.add(Double.valueOf(record.getTotalAverageScore()));
                }
            }
        }
        Integer i20 = 0;
        Integer i40 = 0;
        Integer i60 = 0;
        Integer i80 = 0;
        Integer i90 = 0;
        Integer i100 = 0;
        if(!scoreList.isEmpty()){
            for (Double s : scoreList) {
                if(s<=20.0){
                    i20+=1;
                } else if (s<=40.0) {
                    i40+=1;
                } else if (s<=60.0) {
                    i60+=1;
                } else if (s<=80.0) {
                    i80+=1;
                } else if (s<=90.0) {
                    i80+=1;
                } else if (s<=100.0) {
                    i100+=1;
                }
            }
        }
        Integer total = i20 + i40 + i60 + i80 + i90 + i100;
        //计算总得分占比
        if(total!=0){
            NationVo nation20 = new NationVo();
            NationVo nation40 = new NationVo();
            NationVo nation60 = new NationVo();
            NationVo nation80 = new NationVo();
            NationVo nation90 = new NationVo();
            NationVo nation100 = new NationVo();
            nation20.setName("0 - 20分");
            nation40.setName("21 - 40分");
            nation60.setName("41 - 60分");
            nation80.setName("61 - 80分");
            nation90.setName("81 - 90分");
            nation100.setName("91 - 100分");
            getTotalScoreList(nation20,i20,total,totalScoreList);
            getTotalScoreList(nation40,i40,total,totalScoreList);
            getTotalScoreList(nation60,i60,total,totalScoreList);
            getTotalScoreList(nation80,i80,total,totalScoreList);
            getTotalScoreList(nation90,i90,total,totalScoreList);
            getTotalScoreList(nation100,i100,total,totalScoreList);

            totalScorePercentage.add(nation20);
            totalScorePercentage.add(nation40);
            totalScorePercentage.add(nation60);
            totalScorePercentage.add(nation80);
            totalScorePercentage.add(nation90);
            totalScorePercentage.add(nation100);

        }

        resultVO.setTotalScoreList(totalScoreList);
        resultVO.setTotalScorePercentage(totalScorePercentage);

        return Result.ok(resultVO);
    }

    /**
     *
     * @param nationVo 分数饼图信息
     * @param nationI 每个区间的分数数量
     * @param total 总分数
     * @param totalScoreList 分数占比折线图
     */
    public void getTotalScoreList(NationVo nationVo,Integer nationI,Integer total,List<String> totalScoreList){
        DecimalFormat df = new DecimalFormat("#.00");
        if(nationI==0){
            totalScoreList.add("0");
            nationVo.setValue("0");
        }else {
            double v = Double.valueOf(nationI) / total;
            String format = df.format(v);
            totalScoreList.add(format);
            nationVo.setValue(format);
        }
    }

    public void getScoreRange(double score,int[] nums){
        if(score<=60){
            nums[0]+=1;
        }else if (score<=70) {
            nums[1]+=1;
        } else if (score<=80) {
            nums[2]+=1;
        } else if (score<=90) {
            nums[3]+=1;
        } else if (score<=100) {
            nums[4]+=1;
        }
    }

    public void addScoreRange(List<Integer> list,int[] nums){
        list.add(nums[0]);
        list.add(nums[1]);
        list.add(nums[2]);
        list.add(nums[3]);
        list.add(nums[4]);
    }

    public int[] createNums(){
        int[] nums = new int[5];
        nums[0] = 0;
        nums[1] = 0;
        nums[2] = 0;
        nums[3] = 0;
        nums[4] = 0;

        return nums;
    }

    /**
     * 百分制分值
     * 婴幼儿早期教育发展分析满分10分  百分制：10*10
     * 居家场景满分35分     百分制：35*2.85
     * 月子中心场景满分35分  百分制：35*2.85
     * 职业素养测评满分20分  百分制：20*5
     * @return
     */
    @Override
    public Result<?> scoreRangeList() {
        ExaminationCostStatisticScoreRangeVo resultVO = new ExaminationCostStatisticScoreRangeVo();
        DecimalFormat df = new DecimalFormat("#.00");
        List<Integer> zhiDingList = new ArrayList<>();/** 婴幼儿早期教育发展分析折线图 */
        List<Integer> juJiaList = new ArrayList<>();;/** 居家场景折线图 */
        List<Integer> yueZiList = new ArrayList<>();;/** 月子场景折线图 */
        List<Integer> zhiYeList = new ArrayList<>();;/** 职业素养测评折线图 */
        //查询婴幼儿早期教育发展分析裁判打分
        Map<String, String> mapA =new HashMap<>();
        mapA.put("field","A");
        List<ExaminationResultsPoVo> listA = this.baseMapper.listScoreByField(mapA);
        int[] numsA = createNums();
        if(null!=listA && !listA.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listA) {
                getAvgZhiDing(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getAverageScore());
                double v = averageScore * 10;
                getScoreRange(v,numsA);
            }
        }
        addScoreRange(zhiDingList,numsA);

        //查询居家场景裁判打分裁判打分
        Map<String, String> mapB1 =new HashMap<String, String>();
        mapB1.put("field","B1");
        List<ExaminationResultsPoVo> listB1 = this.baseMapper.listScoreByField(mapB1);
        int[] numsB1  = createNums();
        if(null!=listB1 && !listB1.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB1) {
                getAvgJuJia(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getTotalAverageScore());
                double v = averageScore * 2.85;
                getScoreRange(v,numsB1);
            }
        }
        addScoreRange(juJiaList,numsB1);

        //查询月子场景裁判打分裁判打分
        Map<String, String> mapB2 =new HashMap<>();
        mapB2.put("field","B2");
        List<ExaminationResultsPoVo> listB2 = this.baseMapper.listScoreByField(mapB2);
        int[] numsB2 = createNums();
        if(null!=listB2 && !listB2.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                getAvgJuJia(examinationResultsPoVo);
                double averageScore = Double.parseDouble(examinationResultsPoVo.getTotalAverageScore());
                double v = averageScore * 2.85;
                getScoreRange(v,numsB2);
            }
        }
        addScoreRange(yueZiList,numsB2);


        //查询职业素养测评分数
        Map<String, String> mapC =new HashMap<String, String>();
        mapC.put("field","C");
        List<ExaminationResultsPoVo> listC = this.baseMapper.listScoreByField(mapC);
        int[] numsC = createNums();
        if(null!=listC && !listC.isEmpty()){
            for (ExaminationResultsPoVo examinationResultsPoVo : listB2) {
                double v = Double.valueOf(examinationResultsPoVo.getAverageScore()) * 5;
                getScoreRange(v,numsC);
            }
        }
        addScoreRange(zhiYeList,numsC);

        resultVO.setZhiYeList(zhiYeList);
        resultVO.setJuJiaList(juJiaList);
        resultVO.setYueZiList(yueZiList);
        resultVO.setZhiDingList(zhiDingList);
        return Result.ok(resultVO);
    }

    @Override
    public List<StuResultsAVo> getStatisticsByfieldStuIds(String field,List<String> nameTeams) {
        //计算早期教育发展分析得分
        List<StuResultsAVo> stuResultsAVos = this.baseMapper.getStatisticsByfield(field,nameTeams);
        if(stuResultsAVos.isEmpty()){
            return stuResultsAVos;
        }
        for (int i = 0; i < stuResultsAVos.size(); i++) {
            //裁判数量
            int number = 0;
            Double study = 0.00;
            if(Objects.nonNull(stuResultsAVos.get(i).getScore1()) && Double.parseDouble(stuResultsAVos.get(i).getScore1())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore1());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore2()) && Double.parseDouble(stuResultsAVos.get(i).getScore2())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore2());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore3()) && Double.parseDouble(stuResultsAVos.get(i).getScore3())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore3());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore4()) && Double.parseDouble(stuResultsAVos.get(i).getScore4())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore4());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore5()) && Double.parseDouble(stuResultsAVos.get(i).getScore5())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore5());
                number = number+1;
            }
            if(study!=0.00){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            stuResultsAVos.get(i).setStudy(new DecimalFormat("0.00").format(study));
        }
        return stuResultsAVos;
    }

    @Override
    public Page<StuResultsB1Vo> getStatisicsB1ByField(String field, Integer current, Integer size,Integer decryptAll) {
        Page<StuResultsB1Vo> page = new Page<StuResultsB1Vo>(current,size);
        List<StuResultsB1Vo> stuResultsAVos = this.baseMapper.getStatisicsB1ByField(field, page,decryptAll);
        if(stuResultsAVos.isEmpty()){
            page.setRecords(stuResultsAVos);
            return page;
        }
        for (int i = 0; i < stuResultsAVos.size(); i++) {
            //裁判数量
            int number = 0;
            Double study = 0.0;
            if(Objects.nonNull(stuResultsAVos.get(i).getScore1()) && Double.parseDouble(stuResultsAVos.get(i).getScore1())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore1());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore2()) && Double.parseDouble(stuResultsAVos.get(i).getScore2())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore2());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore3()) && Double.parseDouble(stuResultsAVos.get(i).getScore3())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore3());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore4()) && Double.parseDouble(stuResultsAVos.get(i).getScore4())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore4());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore5()) && Double.parseDouble(stuResultsAVos.get(i).getScore5())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore5());
                number = number+1;
            }

            if(study!=0.0){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            stuResultsAVos.get(i).setFinalScore(new DecimalFormat("0.00").format(study));
        }
        page.setRecords(stuResultsAVos);
        return page;
    }


    @Override
    public Page<StuResultsB2Vo> getStatisicsB2ByField(String field, Integer current, Integer size,Integer decryptAll) {
        Page<StuResultsB2Vo> page = new Page<StuResultsB2Vo>(current,size);
        List<StuResultsB2Vo> stuResultsAVos = this.baseMapper.getStatisicsB2ByField(field,page,decryptAll);
        if(stuResultsAVos.isEmpty()){
            page.setRecords(stuResultsAVos);
            return page;
        }
        for (int i = 0; i < stuResultsAVos.size(); i++) {
            //婴幼儿保健护理裁判数量、分数
            int number = 0;
            Double study = 0.0;
            //婴幼儿急救处理裁判数量、分数
            int number2 = 0;
            Double stud2 = 0.0;
            //婴幼儿保健护理算平均分
            if(Objects.nonNull(stuResultsAVos.get(i).getScore1()) && Double.parseDouble(stuResultsAVos.get(i).getScore1())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore1());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore2()) && Double.parseDouble(stuResultsAVos.get(i).getScore2())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore2());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore3()) && Double.parseDouble(stuResultsAVos.get(i).getScore3())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore3());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore4()) && Double.parseDouble(stuResultsAVos.get(i).getScore4())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore4());
                number = number+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore5()) && Double.parseDouble(stuResultsAVos.get(i).getScore5())>-1){
                study = study+Double.parseDouble(stuResultsAVos.get(i).getScore5());
                number = number+1;
            }

            //婴幼儿急救处理算平均分
            if(Objects.nonNull(stuResultsAVos.get(i).getScore1s()) && Double.parseDouble(stuResultsAVos.get(i).getScore1s())>-1){
                stud2 = stud2+Double.parseDouble(stuResultsAVos.get(i).getScore1s());
                number2 = number2+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore2s()) && Double.parseDouble(stuResultsAVos.get(i).getScore2s())>-1){
                stud2 = stud2+Double.parseDouble(stuResultsAVos.get(i).getScore2s());
                number2 = number2+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore3s()) && Double.parseDouble(stuResultsAVos.get(i).getScore3s())>-1){
                stud2 = stud2+Double.parseDouble(stuResultsAVos.get(i).getScore3s());
                number2 = number2+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore4s()) && Double.parseDouble(stuResultsAVos.get(i).getScore4s())>-1){
                stud2 = stud2+Double.parseDouble(stuResultsAVos.get(i).getScore4s());
                number2 = number2+1;
            }
            if(Objects.nonNull(stuResultsAVos.get(i).getScore5s()) && Double.parseDouble(stuResultsAVos.get(i).getScore5s())>-1){
                stud2 = stud2+Double.parseDouble(stuResultsAVos.get(i).getScore5s());
                number2 = number2+1;
            }
            stuResultsAVos.get(i).setFinalScore(new DecimalFormat("0.00").format((study/number)+(stud2/number2)));
            if(study!=0.0){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            if(stud2 != 0.0){
                stud2 = new BigDecimal(stud2).divide(BigDecimal.valueOf(number2), 2, RoundingMode.HALF_UP).doubleValue();
            }
            stuResultsAVos.get(i).setFinalScore(new BigDecimal(study + stud2).setScale(2,RoundingMode.HALF_UP).toString());
        }
        page.setRecords(stuResultsAVos);
        return page;
    }

    @Override
    public Page<StuResultsTotalVo> getStuResulteTotal(Integer current, Integer size) {
        //初始化返回数据
        List<StuResultsTotalVo> stuResuls = new ArrayList<>();
        //分页查询团队信息
        Page<StuResultsTeamAVo> teamPage = careStuSignUpComRealityService.getTeam(current, size,1,null);
        if(teamPage.getRecords().isEmpty()){
            return setPage(teamPage,stuResuls,current,size);
        }
        //获取团队名称集合
        List<String> nameTeams = teamPage.getRecords().stream().map(StuResultsTeamAVo::getUnitName).collect(Collectors.toList());
        //根据团队集合查询选手成绩信息
        List<StuResultsTotalDto> stuResultsTotalDtos = this.baseMapper.getStuResulteTotal(nameTeams);
        if(stuResultsTotalDtos.isEmpty()){
            return setPage(teamPage,stuResuls,current,size);
        }
        //拼接团队信息
        teamPage.getRecords().forEach(a->{
            StuResultsTotalVo resultsTotalVo = new StuResultsTotalVo();
            BeanUtils.copyProperties(a,resultsTotalVo);
            resultsTotalVo.setRecordNumber(Integer.parseInt(a.getRecordNumber()));
            stuResuls.add(resultsTotalVo);
        });
        //给团队赋值成员成绩信息
        stuResuls.forEach(a->{
            a = setResults(stuResultsTotalDtos,"A",a);
            a = setResults(stuResultsTotalDtos,"B1",a);
            a = setResults(stuResultsTotalDtos,"B2",a);
            a = setResults(stuResultsTotalDtos,"B3",a);
            //计算团队总成绩
            a.setTeamsCoreTotal(String.valueOf(
                    Optional.ofNullable(a.getFinallyScoreA()).orElse(0.00)+
                    Optional.ofNullable(a.getFinallyScoreB()).orElse(0.00)+
                    Optional.ofNullable(a.getFinallyScoreC()).orElse(0.00)+
                    Optional.ofNullable(a.getFinallyScoreD()).orElse(0.00)));
            a.setTeamsCoreTotal(new BigDecimal(a.getTeamsCoreTotal()).setScale(2,RoundingMode.HALF_UP).toString());
        });
        //根据检录序号排序
        List<StuResultsTotalVo> stus = stuResuls.stream().filter(a-> Objects.nonNull(a.getRecordNumber())).sorted(Comparator.comparingInt(StuResultsTotalVo::getRecordNumber)).collect(Collectors.toList());
        //返回最终结果集
        return setPage(teamPage,stus,current,size);
    }


    /**
     * 赋予不同赛场选手团队信息
     * @param stuResultsTotalDtos
     * @param field
     * @param a
     * @return
     */
    public StuResultsTotalVo setResults(List<StuResultsTotalDto> stuResultsTotalDtos,String field,StuResultsTotalVo a){
        List<StuResultsTotalDto> list =  stuResultsTotalDtos.stream()
                .filter(b-> StringUtil.notEmpty(b.getField())&&StringUtil.notEmpty(b.getUnitName()))
                .filter(b->b.getUnitName().equals(a.getUnitName()) && b.getField().equals(field))
                .collect(Collectors.toList());
        if(list.isEmpty()){
            return a;
        }
        //如果是理论
        if("A".equals(field) && list.size()==3){
            a.setNameOne(list.get(0).getName());
            a.setNum1OneA(list.get(0).getNum1());
            a.setNum2OneA((list.get(0).getNum2()));
            a.setTotalScoreOne(list.get(0).getTotalScore());
            a.setScoreAOneTotal(list.get(0).getScoreOne());

            a.setNameTwo(list.get(1).getName());
            a.setNum2TwoA(list.get(1).getNum1());
            a.setNum1TwoA(list.get(1).getNum2());
            a.setTotalScoreTwo(list.get(1).getTotalScore());
            a.setScoreATwoTotal(list.get(1).getScoreOne());

            a.setNameThree(list.get(2).getName());
            a.setNum1ThreeA(list.get(2).getNum1());
            a.setNum2ThreeA(list.get(2).getNum2());
            a.setTotalScoreThree(list.get(2).getTotalScore());
            a.setScoreAThreeTotal(list.get(2).getScoreOne());
            //获取A赛场最终得分
            a.setFinallyScoreA(setFinallyScoreA(list));
        }
        if("B1".equals(field) && list.size()==1){
            a.setNum1B(list.get(0).getNum1());
            a.setNum2B(list.get(0).getNum2());
            a.setScoreBTotal(list.get(0).getScoreOne());
            a.setFinallyScoreB(setFinallyScoreB1(list));
            //获取B1赛场最终得分
            a.setFinallyScoreB(setFinallyScoreB1(list));
        }
        if("B2".equals(field)&& list.size()==1){
            a.setNum1C(list.get(0).getNum1());
            a.setNum2C(list.get(0).getNum2());
            a.setScoreCTotalOne(list.get(0).getScoreOne());
            a.setScoreCTotalOTwo(list.get(0).getScoreTow());
            a.setFinallyScoreC(setFinallyScoreB1(list));
            //获取B2赛场最终得分
            a.setFinallyScoreC(setFinallyScoreB2(list));
        }
        if("B3".equals(field)&& list.size()==1){
            a.setNum1D(list.get(0).getNum1());
            a.setNum2D(list.get(0).getNum2());
            a.setScoreDTotal(list.get(0).getScoreOne());
            a.setFinallyScoreD(setFinallyScoreB1(list));
            //获取B2赛场最终得分
            a.setFinallyScoreD(setFinallyScoreB1(list));
        }
        return a;
    }


    /**
     * 计算B1赛场得分
     * @param list
     * @return
     */
    public Double setFinallyScoreB2(List<StuResultsTotalDto> list) {
        //婴幼儿保健护理裁判数量、分数
        int number = 0;
        Double study = 0.0;
        //婴幼儿急救处理裁判数量、分数
        int number2 = 0;
        Double stud2 = 0.0;
        for (int i = 0; i < list.size(); i++) {
            //婴幼儿保健护理算平均分
            if (Objects.nonNull(list.get(i).getScore1()) && list.get(i).getScore1() > -1) {
                study = study + list.get(i).getScore1();
                number = number + 1;
            }
            if (Objects.nonNull(list.get(i).getScore2()) && list.get(i).getScore2() > -1) {
                study = study + list.get(i).getScore2();
                number = number + 1;
            }
            if (Objects.nonNull(list.get(i).getScore3()) && list.get(i).getScore3() > -1) {
                study = study + list.get(i).getScore3();
                number = number + 1;
            }
            if (Objects.nonNull(list.get(i).getScore4()) && list.get(i).getScore4() > -1) {
                study = study + list.get(i).getScore4();
                number = number + 1;
            }
            if (Objects.nonNull(list.get(i).getScore5()) && list.get(i).getScore5() > -1) {
                study = study + list.get(i).getScore5();
                number = number + 1;
            }

            //婴幼儿急救处理算平均分
            if (Objects.nonNull(list.get(i).getScore1s()) && list.get(i).getScore1s() > -1) {
                stud2 = stud2 + list.get(i).getScore1s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(list.get(i).getScore2s()) && list.get(i).getScore2s() > -1) {
                stud2 = stud2 + list.get(i).getScore2s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(list.get(i).getScore3s()) && list.get(i).getScore3s() > -1) {
                stud2 = stud2 + list.get(i).getScore3s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(list.get(i).getScore4s()) && list.get(i).getScore4s() > -1) {
                stud2 = stud2 + list.get(i).getScore4s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(list.get(i).getScore5s()) && list.get(i).getScore5s() > -1) {
                stud2 = stud2 + list.get(i).getScore5s();
                number2 = number2 + 1;
            }
            list.get(i).setFinalScore((study / number) + (stud2 / number2));
            if (study != 0.0) {
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            if (stud2 != 0.0) {
                stud2 = new BigDecimal(stud2).divide(BigDecimal.valueOf(number2), 2, RoundingMode.HALF_UP).doubleValue();
            }
        }
        return new BigDecimal(study + stud2).setScale(2,RoundingMode.HALF_UP).doubleValue();
    }





    /**
     * 计算B1赛场得分
     * @param list
     * @return
     */
    public Double setFinallyScoreB1(List<StuResultsTotalDto> list){
        //裁判数量
        int number = 0;
        //裁判打分总和
        Double study = 0.0;
        for (int i = 0; i < list.size(); i++) {
            if(Objects.nonNull(list.get(i).getScore1()) && list.get(i).getScore1()>-1){
                study = study+list.get(i).getScore1();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore2()) && list.get(i).getScore2()>-1){
                study = study+list.get(i).getScore2();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore3()) && list.get(i).getScore3()>-1){
                study = study+list.get(i).getScore3();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore4()) && list.get(i).getScore4()>-1){
                study = study+list.get(i).getScore4();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore5()) && list.get(i).getScore5()>-1){
                study = study+list.get(i).getScore5();
                number = number+1;
            }
            if(study!=0.0){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
        }
        return study;
    }



    /**
     * 计算理论总得分
     * @param list
     * @return
     */
    public Double setFinallyScoreA(List<StuResultsTotalDto> list){
        Double teamsCore = 0.0;
        for (int i = 0; i < list.size(); i++) {
            //裁判数量
            int number = 0;
            //裁判打分总和
            Double study = 0.0;
            if(Objects.nonNull(list.get(i).getScore1()) && list.get(i).getScore1()>-1){
                study = study+list.get(i).getScore1();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore2()) && list.get(i).getScore2()>-1){
                study = study+list.get(i).getScore2();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore3()) && list.get(i).getScore3()>-1){
                study = study+list.get(i).getScore3();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore4()) && list.get(i).getScore4()>-1){
                study = study+list.get(i).getScore4();
                number = number+1;
            }
            if(Objects.nonNull(list.get(i).getScore5()) && list.get(i).getScore5()>-1){
                study = study+list.get(i).getScore5();
                number = number+1;
            }

            if(study!=0.0){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            teamsCore = teamsCore +
                    Optional.ofNullable(list.get(i).getTotalScore()).orElse(0.0) +
                    Optional.ofNullable(study).orElse(0.0);
        }
        if(teamsCore>0.0){
            return new BigDecimal(teamsCore).divide(BigDecimal.valueOf(list.size()), 2, RoundingMode.HALF_UP).doubleValue();
        }
        return 0.0;
    }




    /**
     * 拼接分页信息
     * @param teamPage
     * @param stuResuls
     * @param current
     * @param size
     * @return
     */
    private Page<StuResultsTotalVo> setPage(Page<StuResultsTeamAVo> teamPage,List<StuResultsTotalVo> stuResuls,Integer current, Integer size){
        Page<StuResultsTotalVo> page = new Page<StuResultsTotalVo>(current,size);
        page.setTotal(teamPage.getTotal());
        page.setRecords(stuResuls);
        page.setSize(teamPage.getSize());
        page.setCurrent(teamPage.getCurrent());
        return page;
    }

    @Override
    public void documenResulte(HttpServletResponse respons){
        List<StuResultsTotalVo> stus = setStuResults();
        //返回最终结果集
        EasyPoiUtil.exportExcel(stus, "成绩总统计导出", "成绩总统计导出", StuResultsTotalVo.class, "成绩总统计导出", respons);
    }


    /**
     * 获取总统计数据
     */
    public List<StuResultsTotalVo> setStuResults(){
        //初始化返回数据
        List<StuResultsTotalVo> stuResuls = new ArrayList<>();
        //分页查询团队信息
        Page<StuResultsTeamAVo> teamPage = careStuSignUpComRealityService.getTeam(1, 1000,1,null);
        if(teamPage.getRecords().isEmpty()){
            return stuResuls;
        }
        //获取团队名称集合
        List<String> nameTeams = teamPage.getRecords().stream().map(StuResultsTeamAVo::getUnitName).collect(Collectors.toList());
        //根据团队集合查询选手成绩信息
        List<StuResultsTotalDto> stuResultsTotalDtos = this.baseMapper.getStuResulteTotal(nameTeams);
        if(stuResultsTotalDtos.isEmpty()){
            return stuResuls;
        }
        //拼接团队信息
        teamPage.getRecords().forEach(a->{
            StuResultsTotalVo resultsTotalVo = new StuResultsTotalVo();
            BeanUtils.copyProperties(a,resultsTotalVo);
            resultsTotalVo.setRecordNumber(Integer.parseInt(a.getRecordNumber()));
            stuResuls.add(resultsTotalVo);
        });
        //给团队赋值成员成绩信息
        stuResuls.forEach(a->{
            a = setResults(stuResultsTotalDtos,"A",a);
            a = setResults(stuResultsTotalDtos,"B1",a);
            a = setResults(stuResultsTotalDtos,"B2",a);
            a = setResults(stuResultsTotalDtos,"B3",a);
            //计算团队总成绩
            a.setTeamsCoreTotal(String.valueOf(
                    Optional.ofNullable(a.getFinallyScoreA()).orElse(0.0)+
                            Optional.ofNullable(a.getFinallyScoreB()).orElse(0.0)+
                            Optional.ofNullable(a.getFinallyScoreC()).orElse(0.0)+
                            Optional.ofNullable(a.getFinallyScoreD()).orElse(0.0)));
            a.setTeamsCoreTotal(new BigDecimal(a.getTeamsCoreTotal()).setScale(2,RoundingMode.HALF_UP).toString());
        });
        //根据总成绩排序
        List<StuResultsTotalVo> stus = stuResuls.stream().filter(a-> Objects.nonNull(a.getRecordNumber())).sorted(Comparator.comparingInt(StuResultsTotalVo::getRecordNumber)).collect(Collectors.toList());
        return stus;
    }



    @Override
    public void documentResulteWord(HttpServletResponse respons) throws Exception{
        List<StuResultsTotalVo> stus = setStuResults();
        //导出组装数据
        Map<String,Object> params =new HashMap<>();
        //暂定
        params.put("batchName","婴幼儿照护");
        List<StuResultsTotalVo> listStu = new ArrayList<>();
        if(stus!=null && !stus.isEmpty()){
            listStu = stus.stream()
                    .sorted((vo1, vo2) -> {
                        try {
                            double score1 = Double.parseDouble(vo1.getTeamsCoreTotal());
                            double score2 = Double.parseDouble(vo2.getTeamsCoreTotal());
                            return Double.compare(score2, score1); // 降序排序
                        } catch (NumberFormatException e) {
                            // 处理无法解析的情况，可以决定它们的相对顺序
                            // 这里假设无法解析的字符串应被视为最低分数
                            return 1; // vo1 排在 vo2 后面，实现降序效果
                        }
                    })
                    .collect(Collectors.toList());
            for (int i = 1; i <= listStu.size(); i++) {
                listStu.get(i-1).setSort(i);
            }
        }

        params.put("listStu",listStu);
        XWPFDocument word = WordExportUtil.exportWord07(templateFile().getPath(),params);
        respons.setHeader("content-disposition","attachment;filename="+new String("成绩公示表.docx".getBytes(),"ISO8859-1"));
        respons.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        word.write(respons.getOutputStream());
    }

    @Override
    public Result proportionOfTotalScore() {
        List<ModuleScoreProportionVo> vos = new ArrayList<>();
        //查询所有成绩信息
        List<ExaminationResultsComDO>  results = this.selectList(new EntityWrapper<ExaminationResultsComDO>());
        if(results.isEmpty()){
            return Result.ok(vos);
        }
        //获取A赛场得分
        List<ExaminationResultsComDO>  resultsA  = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("A"))
                .collect(Collectors.toList()),"A");
        if(!resultsA.isEmpty()){
            vos.add(getNumberScour(resultsA,ResulitsConfig.Knowledge_assessment,"婴幼儿照护综合知识测评"));
        }
        //B1赛场
        List<ExaminationResultsComDO>  resultsB1 = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B1"))
                .collect(Collectors.toList()),"B1");
        if(!resultsB1.isEmpty()){
            vos.add(getNumberScour(resultsB1,ResulitsConfig.Life_care,"婴幼儿生活照料"));
        }

        //B2赛场
        List<ExaminationResultsComDO>  resultsB2 = setScoreIntervalB2(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B2"))
                .collect(Collectors.toList()));
        if(!resultsB2.isEmpty()){
            vos.add(getNumberB2Scour(resultsB2,ResulitsConfig.Health_care,"婴幼儿保健护理"));
            vos.add(getNumberB2Scour(resultsB2,ResulitsConfig.First_aid_treatment,"婴幼儿急救处理"));
        }

        //B3赛场
        List<ExaminationResultsComDO>  resultsB3 = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B3"))
                .collect(Collectors.toList()),"B3");
        if(!resultsB3.isEmpty()){
            vos.add(getNumberScour(resultsB3,ResulitsConfig.Activity_design,"婴幼儿早期发展亲子活动设计"));
        }

        return Result.ok(vos);
    }

    /**
     * 获取分值
     * @param results
     * @param scour
     * @return
     */
    public ModuleScoreProportionVo getNumberScour(List<ExaminationResultsComDO> results,Double scour,String field){
        Double[] min = {0.0,61.0,71.0,81.0,91.0};
        Double[] max = {60.0,70.0,80.0,90.0,100.0};
        Integer[] takeScore = new Integer[5];
        for (int i = 0; i < takeScore.length; i++) {
            int j = i;
            takeScore[i] = Optional.of(
                    Math.toIntExact(results.stream()
                            .filter(a ->
                                    BigDecimal.valueOf(a.getTotalScore())
                                            .divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 >= min[j]
                                            &&
                                            BigDecimal.valueOf(a.getTotalScore())
                                                    .divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 <= max[j])
                            .count())).orElse(0);
        }
    return new ModuleScoreProportionVo(field,takeScore[0],takeScore[1],takeScore[2],takeScore[3],takeScore[4]);
    }



    public ModuleScoreProportionVo getNumberB2Scour(List<ExaminationResultsComDO>  resultsA,Double scour,String field){
        Double[] min = {0.0,61.0,71.0,81.0,91.0};
        Double[] max = {60.0,70.0,80.0,90.0,100.0};
        Integer[] takeScore = new Integer[5];
        for (int i = 0; i < takeScore.length; i++) {
            int j = i;
            if(field.equals("婴幼儿保健护理")){
                takeScore[i] = Optional.of(
                        Math.toIntExact(resultsA.stream()
                                .filter(a ->
                                        BigDecimal.valueOf(a.getScoreB1()).divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 >= min[j]
                                                &&
                                                BigDecimal.valueOf(a.getScoreB1()).divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 <= max[j])
                                .count())).orElse(0);
            }else{
                takeScore[i] = Optional.of(
                        Math.toIntExact(resultsA.stream()
                                .filter(a ->
                                        BigDecimal.valueOf(a.getScoreB2()).divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 >= min[j]
                                                &&
                                                BigDecimal.valueOf(a.getScoreB2()).divide(BigDecimal.valueOf(scour), 2, RoundingMode.HALF_UP).doubleValue() * 100 <= max[j])
                                .count())).orElse(0);
            }
        }
        return new ModuleScoreProportionVo(field,takeScore[0],takeScore[1],takeScore[2],takeScore[3],takeScore[4]);
    }


    @Override
    public ProportionOfTotalScoreVo moduleScoreProportion() {
        Page<StuResultsTotalVo> results = getStuResulteTotal(1,1000);
        Double[] min = {0.0,21.0,41.0,61.0,81.0,91.0};
        Double[] max = {20.0,40.0,60.0,80.0,90.0,100.0};
        Integer[] takeScore = new Integer[6];
        for (int i = 0; i < takeScore.length; i++) {
            int j = i;
                takeScore[i] = Optional.of(
                        Math.toIntExact(results.getRecords().stream()
                                .filter(a -> Double.parseDouble(a.getTeamsCoreTotal()) >= min[j]
                                                &&
                                        Double.parseDouble(a.getTeamsCoreTotal()) <= max[j])
                                .count())).orElse(0);
        }
        return new ProportionOfTotalScoreVo(takeScore[0],takeScore[1],takeScore[2],takeScore[3],takeScore[4],takeScore[5]);
    }

    @Override
    public Result scoreInterval() {
        List<ScoreIntervalVo> vos = new ArrayList<>();
        //查询所有成绩信息
        List<ExaminationResultsComDO>  results = this.selectList(new EntityWrapper<ExaminationResultsComDO>());
        if(results.isEmpty()){
            return Result.ok(vos);
        }
        //获取A赛场得分
        List<ExaminationResultsComDO>  resultsA  = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("A")).collect(Collectors.toList()),"A");
        if(!resultsA.isEmpty()){
            DoubleSummaryStatistics stats = resultsA.stream().mapToDouble(ExaminationResultsComDO::getTotalScore).summaryStatistics();
            vos.add(new ScoreIntervalVo("婴幼儿照护综合知识测评",stats));
        }
        //B1赛场
        List<ExaminationResultsComDO>  resultsB1 = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B1")).collect(Collectors.toList()),"B1");
        if(!resultsA.isEmpty()){
            DoubleSummaryStatistics stats = resultsB1.stream().mapToDouble(ExaminationResultsComDO::getTotalScore).summaryStatistics();
            vos.add(new ScoreIntervalVo("婴幼儿生活照料",stats));
        }

        //B2赛场
        List<ExaminationResultsComDO>  resultsB2 = setScoreIntervalB2(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B2")).collect(Collectors.toList()));
        if(!resultsA.isEmpty()){
            DoubleSummaryStatistics stats = resultsB2.stream().mapToDouble(ExaminationResultsComDO::getScoreB1).summaryStatistics();
            vos.add(new ScoreIntervalVo("婴幼儿保健护理",stats));
            DoubleSummaryStatistics stats1 = resultsB2.stream().mapToDouble(ExaminationResultsComDO::getScoreB2).summaryStatistics();
            vos.add(new ScoreIntervalVo("婴幼儿急救处理",stats1));
        }

        //B3赛场
        List<ExaminationResultsComDO>  resultsB3 = setScoreInterval(results.stream().filter(a->Objects.nonNull(a.getField())&& a.getField().equals("B3")).collect(Collectors.toList()),"B3");
        if(!resultsA.isEmpty()){
            DoubleSummaryStatistics stats = resultsB3.stream().mapToDouble(ExaminationResultsComDO::getTotalScore).summaryStatistics();
            vos.add(new ScoreIntervalVo("婴幼儿早期发展亲子活动设计",stats));
        }
        return Result.ok(vos);
    }


    /**
     * @param results
     * @return
     */
    public List<ExaminationResultsComDO> setScoreInterval(List<ExaminationResultsComDO>  results,String field) {
        if(results.isEmpty()){
            return results;
        }
        for (int i = 0; i < results.size(); i++) {
            //裁判数量
            int number = 0;
            Double study = 0.0;
            if(Objects.nonNull(results.get(i).getScore1()) && results.get(i).getScore1()>-1){
                study = study+results.get(i).getScore1();
                number = number+1;
            }
            if(Objects.nonNull(results.get(i).getScore2()) && results.get(i).getScore2()>-1){
                study = study+results.get(i).getScore2();
                number = number+1;
            }
            if(Objects.nonNull(results.get(i).getScore3()) && results.get(i).getScore3()>-1){
                study = study+results.get(i).getScore3();
                number = number+1;
            }
            if(Objects.nonNull(results.get(i).getScore4()) && results.get(i).getScore4()>-1){
                study = study+results.get(i).getScore4();
                number = number+1;
            }
            if(Objects.nonNull(results.get(i).getScore5()) && results.get(i).getScore5()>-1){
                study = study+results.get(i).getScore5();
                number = number+1;
            }
            if(study!=0.0){
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            if(field.equals("A")){
                results.get(i).setTotalScore(study+results.get(i).getTotalScore());
            }else{
                results.get(i).setTotalScore(study);
            }

        }
        return results;
    }



    /**
     * 计算B1赛场得分
     * @param results
     * @return
     */
    public List<ExaminationResultsComDO> setScoreIntervalB2(List<ExaminationResultsComDO>  results) {
        //婴幼儿保健护理裁判数量、分数
        int number = 0;
        Double study = 0.0;
        //婴幼儿急救处理裁判数量、分数
        int number2 = 0;
        Double stud2 = 0.0;
        for (int i = 0; i < results.size(); i++) {
            //婴幼儿保健护理算平均分
            if (Objects.nonNull(results.get(i).getScore1()) && results.get(i).getScore1() > -1) {
                study = study + results.get(i).getScore1();
                number = number + 1;
            }
            if (Objects.nonNull(results.get(i).getScore2()) && results.get(i).getScore2() > -1) {
                study = study + results.get(i).getScore2();
                number = number + 1;
            }
            if (Objects.nonNull(results.get(i).getScore3()) && results.get(i).getScore3() > -1) {
                study = study + results.get(i).getScore3();
                number = number + 1;
            }
            if (Objects.nonNull(results.get(i).getScore4()) && results.get(i).getScore4() > -1) {
                study = study + results.get(i).getScore4();
                number = number + 1;
            }
            if (Objects.nonNull(results.get(i).getScore5()) && results.get(i).getScore5() > -1) {
                study = study + results.get(i).getScore5();
                number = number + 1;
            }

            //婴幼儿急救处理算平均分
            if (Objects.nonNull(results.get(i).getScore1s()) && results.get(i).getScore1s() > -1) {
                stud2 = stud2 + results.get(i).getScore1s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(results.get(i).getScore2s()) && results.get(i).getScore2s() > -1) {
                stud2 = stud2 + results.get(i).getScore2s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(results.get(i).getScore3s()) && results.get(i).getScore3s() > -1) {
                stud2 = stud2 + results.get(i).getScore3s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(results.get(i).getScore4s()) && results.get(i).getScore4s() > -1) {
                stud2 = stud2 + results.get(i).getScore4s();
                number2 = number2 + 1;
            }
            if (Objects.nonNull(results.get(i).getScore5s()) && results.get(i).getScore5s() > -1) {
                stud2 = stud2 + results.get(i).getScore5s();
                number2 = number2 + 1;
            }
            if (study != 0.0) {
                study = new BigDecimal(study).divide(BigDecimal.valueOf(number), 2, RoundingMode.HALF_UP).doubleValue();
            }
            if (stud2 != 0.0) {
                stud2 = new BigDecimal(stud2).divide(BigDecimal.valueOf(number2), 2, RoundingMode.HALF_UP).doubleValue();
            }
            results.get(i).setScoreB1(study);
            results.get(i).setScoreB2(stud2);

        }
        return results;
    }

    @Override
    public Result stuFileDownload(HttpServletResponse response){
        //获取竞赛名称
        String baName = this.selectOne(new ExaminationResultsComDO()).getName();
        //获取所有真是考生信息
        List<CareStuSignUpComRealityDO> signs = careStuSignUpComRealityService.selectList(new EntityWrapper<CareStuSignUpComRealityDO>());
        if(signs.isEmpty()){
            return Result.fail("考生信息为空");
        }
        List<Long> stuIds = signs.stream().map(CareStuSignUpComRealityDO::getId).collect(Collectors.toList());
        //根据考生id集合获取考生文件链接
        List<ExaminationAnswerSheetComDO> exs = examinationAnswerSheetComService.selectList(new
                EntityWrapper<ExaminationAnswerSheetComDO>().in("stu_sign_id",stuIds));
        //筛选出有附件的考生答卷
        List<ExaminationAnswerSheetComDO> files = exs.stream().filter(a -> !StringUtils.isBlank(a.getFile())).distinct().collect(Collectors.toList());
        if(files.isEmpty()){
            return Result.fail("没有可下载的附件");
        }
        //添加二次加密号
        files.forEach(a -> signs.forEach(b ->{
            if(Objects.equals(a.getStuSignId(),b.getId())){
                a.setNum2(b.getNum2());
            }
        }));
        Map<String, String> map =new HashMap<>();
        map.put("type","foundZip");
        map.put("name","foundZip");
        String foundZip = dictService.selDicBy(map);
        //调用文件接口
        return Result.ok(foundZip(files,baName,response,foundZip));
    }


    /**
     * 封装文件接口
     */
    private String foundZip(List<ExaminationAnswerSheetComDO> files,String baName,HttpServletResponse response,String foundZip){
        try {
            List<File> file = new ArrayList<>();
            for (int j = 0; j < files.size(); j++) {
                URL url = new URL(files.get(j).getFile());
                String fileName = url.getFile();
                // 打开到该URL的连接
                URLConnection conn = url.openConnection();
                // 从连接中获取输入流
                InputStream in = conn.getInputStream();
                // 创建一个临时文件来存储下载的映像
                Date date = new Date();
                String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
                File tempFile = File.createTempFile("A"+files.get(j).getNum2().toString()+"-" + dateStr +"-",  fileName.substring(fileName.lastIndexOf(".")));
                // 创建一个输出流，将映像写入临时文件
                FileOutputStream out = new FileOutputStream(tempFile);
                // 从输入流中读取文件并将其写入输出流
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                // 关闭输入和输出流
                in.close();
                out.close();
                // 打印临时文件的路径
                System.out.println("Downloaded file saved as "+tempFile.getAbsolutePath());
                File file1  = new File(tempFile.getAbsolutePath());
                file.add(file1);

            }
            String fileName = foundZip + baName + ".zip";
            System.out.println("Downloaded Zip saved as"+fileName);
            //压缩文件
            ZipFileUtils.generateZip(new File(fileName), file, false);
            //下载文件
            //ZipFileUtils.download(new File(fileName),response);
            //ZipFileUtils.downloadZip(new File(fileName),response);
            //把临时文件上传至服务器
            File filess = new File(fileName);
            MultipartFile cMultiFile = new MockMultipartFile("file", filess.getName(), null, new FileInputStream(filess));
            //上传成功后删除临时文件
            filess.delete();
            return fileController.upload(cMultiFile).getData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {

        }
    }

}
